#pragma once

#include <iostream>
#include <functional>
#include <memory>
#include "socket.hpp"
#include "RequestAndRespond.hpp"

using process_t = std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)>; 

class IOservice
{
private:
    process_t _process;
public:
    IOservice(process_t process)
        :_process(process)
    {
    }
    void Excute(SockSPtr sock, InetAddr &addr)
    {
        std::string packagestream;
        while (true)
        {
            ssize_t n = sock->Recv(&packagestream);
            if (n <= 0)
            {
                LOG(INFO, "client: %s, quit\n", addr.AddrStr().c_str());
                break;
            }
            // 得到不完整报文 
            std::string package = deEnCode(packagestream);
            if (package.empty()) continue;
            // 得到完成报文
            auto req = Factory::BuildRequestDefault(); // 创建请求
            req->Deserialize(package); // 反序列化

            auto resp = _process(req); //通过请求得到应答

            std::string respjson;
            resp->Serialize(&respjson);
            respjson = enCode(respjson);

            sock->Send(respjson);
        }
    }
    ~IOservice()
    {
    }
};